import { Sequelize } from 'sequelize-typescript';
import { Conversation } from './models/conversation';
import { Message } from './models/messages';

export class DBDataContext {
    static Current = new DBDataContext();
    private conn: Sequelize;
    get Conn() {
        return this.conn;
    }

    get DirName() {
        return __dirname;
    }

    get Database() {
        return 'coeus_coder';
    }
    async GetTransaction() {
        if (!this.conn) {
            throw new Error('DBDataContext not init');
        }
        return this.conn.transaction();
    }


    async SyncSqlitDB() {
        for (const modelkey in this.conn.models) {
            try {
                const entityModel = this.conn.models[modelkey];
                await entityModel.sync({ alter: true });
            } catch (error) {
                console.error(error);
            }
        }
    }

    async SyncDB() {
        try {
            if (this.conn) {
                await this.conn.sync({ alter: { drop: false } });
            }
        } catch (error) {
            console.error(error);
        }
    }

    async Connect() {
        console.log(process.env.USER_DIR, this.Database);
        this.conn = new Sequelize({
            database: this.Database,
            dialect: "sqlite",
            storage: process.env.USER_DIR + this.Database + ".sqlite",
            models: [Conversation, Message],
            logging: false,
        });
        console.log('constructor DBDataContext', this.DirName, this.Database);
    }

    async TestConnection() {
        try {
            if (this.conn) {
                await this.conn.authenticate();
                global.logger.info(`Connection to [${this.Database}] has been established successfully.`);
            } else {
                global.logger.info(`The database [${this.Database}] is not connected`);
            }
        } catch (error) {
            global.logger.error('Unable to connect to the database:', error);
        }
    }

    async Close() {
        if (this.conn) {
            await this.conn.close();
        }
    }
}
